package com.landscope.issue.service.applet;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.landscope.issue.entity.Token;
import com.landscope.issue.mapper.TokenMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class TokenService {
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String APP_ID = "wx08af4de0a76d53cd";
    private static final String APP_SECRET = "462d766a9a80e516e7a6f2c1cf39dddf";

    @Resource
    private TokenMapper tokenMapper;

    public void refreshToken() {
        Token token = tokenMapper.findByName("weixin");
        if (token == null) {
            getToken();
        } else if (token.getAccessTokenExpiredTime() == null || token.getAccessTokenExpiredTime().getTime() - 60000 < System.currentTimeMillis()) {
            // 如果已超时，则重新刷新,提前一分钟
            getToken();
        }
    }

    public void getToken() {
        if (StringUtil.isEmpty(APP_ID) || StringUtil.isEmpty(APP_SECRET)) {
            log.info("APP_ID或APP_SECRET为空，不请求token");
            return;
        }
        String url = GET_ACCESS_TOKEN_URL + "?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        log.info("刷新微信AccessToken请求:{}", url);
        String res = HttpUtil.get(url);
        log.info("刷新微信AccessToken结果:{}", res);
        JSONObject obj = JSONObject.parseObject(res);
        if (obj != null && obj.get("access_token") != null && obj.get("expires_in") != null) {
            String access_token = obj.getString("access_token");
            Integer expires_in = obj.getInteger("expires_in");

            // 保存token
            Token token = tokenMapper.findByName("weixin");
            if (token == null) {
                token = new Token();
                token.setName("weixin");
                token.setAccessToken(access_token);
                token.setRes("微信AccessToken");
                token.setAccessTokenExpiredTime(new Date(System.currentTimeMillis() + expires_in * 1000));
                tokenMapper.insertSelective(token);
            } else {
                token.setAccessToken(access_token);
                token.setUpdateTime(new Date());
                token.setAccessTokenExpiredTime(new Date(System.currentTimeMillis() + expires_in * 1000));
                tokenMapper.updateByPrimaryKeySelective(token);
            }
        }
    }
}
